import re
from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render, redirect
from QQLoginTool.QQtool import OAuthQQ
# Create your views here.
from django.urls import reverse
from django.utils import http
from django.views import View
from django.http import HttpResponseBadRequest
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generic_openid_token, check_openid_token
from apps.users.models import User
from utils.response_code import RETCODE
from meiduo_mall import settings
import logging
logger = logging.getLogger('django')
class OauthQQURLView(View):
    def get(self,request):
        state = request.GET.get('next')
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            redirect_uri=settings.QQ_REDIRECT_URI,
            client_secret=settings.QQ_CLIENT_SECRET,
            state=state
        )
        login_url = qq.get_qq_url()
        # login_url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101518219&redirect_uri=http://www.meiduo.site:8000/oauth_callback&state=test'
        return JsonResponse({'code':RETCODE.OK,'errmag':'OK','login_url':login_url})



class OauthQQUserView(View):
    def get(self,request):
        #1.得到code
        code = request.GET.get('code')
        if code is None:
            return http.HttpRsponseBadrequest('参数错误')


        #2.通过code换取token
        # 2.1 创建OAuthQQ实力
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            redirect_uri=settings.QQ_REDIRECT_URI,
            client_secret=settings.QQ_CLIENT_SECRET,
        )
        # 2.2 通过code换取token
        token = qq.get_access_token(code)
        #3.通过token获取openid
        openid = qq.get_open_id(token)
        try:#4.判断openid对应的user是否存在
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            #对openid进行itsdangerous加密
            openid_token = generic_openid_token(openid)
            #5.不存在跳转绑定页面
            return render(request,'oauth_callback.html',context={'openid':openid_token})
        else:
            #6.存在用户保持登陆状态
            user = qquser.user
            #6.1保持登陆状态
            login(request,user)
            #6.2返回主页面
            response = redirect(reverse("contents:index"))
            #6.3设置cookie
            response.set_cookie('username',user.username,max_age=14*24*3600)
        return render(request, 'oauth_callback.html')
    def post(self, request):
        # 1.接收数据
        data = request.POST
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code_client = data.get('sms_code')
        access_token = data.get('access_token')

        # 2.验证数据
        if not all([mobile,password,sms_code_client]):
            # from django import http
            return HttpResponseBadRequest('参数不全')
        #     手机号

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return HttpResponseBadRequest('手机号码不符合规则')
        #     密码
        if not re.match(r'^[0-9a-zA-Z]{8,20}',password):
            return HttpResponseBadRequest('密码格式不正确')
        #     短信验证码
        redis_conn = get_redis_connection('code')
        # 8.1.2获取redis中的短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        # 8.1.3判断redis中的短信验证码是否过期
        if not sms_code_server:
            return HttpResponseBadRequest("短信验证码过期")
        # 8.1.4对比
        if sms_code_server.decode() != sms_code_client:
            return HttpResponseBadRequest('验证码不一致')
        #     openid_token
        openid = check_openid_token(access_token)
        if openid is None:
            return HttpResponseBadRequest('openid错误')
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile
            )
        else:#如果手机好被注册，已经有uesr信息
             #我们需要再次验证密码是否正确
            if not user.check_password(password):
                return HttpResponseBadRequest("密码错误")
        try:
            OAuthQQUser.objects.create(
                openid=openid,
                user=user
            )
        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('数据库报错')
        #保持状态
        login(request,user)
        #设置cookie
        next = request.GET.get('state')
        if next:
            response = redirect(next)
        else:
            response = redirect(reverse('contents:index'))
        # response = redirect(reverse("contents:index"))
        response.set_cookie('username',user.username,max_age=14*24*3600)
        #返回相应
        return response